package com.snow.rbac.controller;


import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.snow.common.base.R;
import com.snow.common.base.ResponseCode;
import com.snow.rbac.entity.UserInfo;
import com.snow.rbac.entity.dto.AddUserInfoDto;
import com.snow.rbac.entity.vo.UserInfoVo;
import com.snow.rbac.service.IUserInfoService;
import com.snow.rbac.util.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Yanke
 * @since 2021-06-16
 */
@RestController
@RequestMapping("/rbac/user-info")
public class UserInfoController {

    @Autowired
    IUserInfoService userInfoService;

    @GetMapping("/{id}")
    public R<UserInfo> id(@PathVariable Long id) {
        UserInfo userInfo = userInfoService.getById(id);
        Assert.notNull(userInfo, () -> ResponseCode.BUSINESSEXCEPTION_1002.getCode());
        return R.ok(userInfo);
    }

    @PostMapping("/addUser")
    public R addUser(@RequestBody AddUserInfoDto userInfoDto) {
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        userInfoDto.setPassword(md5.digestHex(userInfoDto.getPassword()));
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoDto, userInfo);
        userInfoService.save(userInfo);
        return R.ok();
    }

    @PostMapping("/login")
    public UserInfoVo login(String username, String password) {
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(md5.digestHex(password));
        UserInfo info = userInfoService.getOne(new QueryWrapper<>(userInfo), false);
        Assert.notNull(userInfo, () -> ResponseCode.BUSINESSEXCEPTION_1002.getCode());

        String token = JwtUtils.createJwt(JSON.parseObject(JSON.toJSONString(info), Map.class));

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(info, userInfoVo, "password");
        userInfoVo.setToken(token);
        return userInfoVo;
    }
}
